package leetcode.concurrency;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 按序打印
 * @author jiangwz
 * @create 2019/11/6.
 */
public class Q1114 {

    public static void main(String[] args){
        Foo foo = new Foo();
        new Thread(() -> {
            try {
                foo.first(() -> System.out.print("one"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "1").start();
        new Thread(() -> {
            try {
                foo.second(() -> System.out.print("two"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "2").start();
        new Thread(() -> {
            try {
                foo.third(() -> System.out.print("three"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "3").start();

    }

}

class Foo {

//    private Semaphore second = new Semaphore(0);
//    private Semaphore third = new Semaphore(0);

    BlockingQueue<Integer> second = new LinkedBlockingQueue<>();
    BlockingQueue<Integer> third = new LinkedBlockingQueue<>();

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {
        // printFirst.run() outputs "first". Do not change or remove this line.

        printFirst.run();
        second.add(1);
//        second.release();
    }

    public void second(Runnable printSecond) throws InterruptedException {

        // printSecond.run() outputs "second". Do not change or remove this line.
//        second.acquire();
        second.take();
        printSecond.run();
        third.add(1);
//        third.release();
    }

    public void third(Runnable printThird) throws InterruptedException {

        // printThird.run() outputs "third". Do not change or remove this line.
//        third.acquire();
        third.take();
        printThird.run();
    }
}